package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.service.ApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Slf4j
@Service
public class MInIOService {

    @Autowired
    private ApArticleService apArticleService;
    @Autowired
    private Configuration configuration;


    @Autowired
    private FileStorageService fileStorageService;


    @Autowired
    private  EsService esService;


    @Async
    public void sendMInIO(ApArticleContent apArticleContent) {

        try {
            String content = apArticleContent.getContent();
            JSONArray contentList = JSON.parseArray(content);

            Template template = configuration.getTemplate("article.ftl");
            HashMap date = new HashMap();
            date.put("content", contentList);
            StringWriter stringWriter = new StringWriter();
            template.process(date, stringWriter);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
            String staticUrl = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", inputStream);

            Long articleId = apArticleContent.getArticleId();
            LambdaUpdateWrapper<ApArticle> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(ApArticle::getId,apArticleContent.getArticleId());
            lambdaUpdateWrapper.set(ApArticle::getStaticUrl,staticUrl);
            apArticleService.update(lambdaUpdateWrapper);

            esService.updateToEs(articleId);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
